<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\model\AdminMenu;
use app\validate\LoginValidate;
use app\model\Admin;
use think\exception\ValidateException;
use xiaodi\JWTAuth\Facade\Jwt;

class AccountController
{

    /**
     * @param Admin $adminModel
     * @return \think\response\Json
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    public function login(Admin $adminModel,AdminMenu $AdminMenu): \think\response\Json
    {
        if (request()->isPost()) {
            $param = request()->only(['account','password']);

            // 检验完整性
            try {
                validate(LoginValidate::class)->scene('login')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $where = ['account' => $param['account']];
            $admin = $adminModel->getAdmin($where,['role'])['data'];
            if (!checkPassword($param['password'], $admin['password'])) {
                return jsonReturn(-2, '用户名密码不正确');
            }
            if ($admin['status'] == 2) {
                return jsonReturn(-3, '该账号已经被禁用');
            }
            // TODO 缓存其权限数据
            // 获取权限
            $role = $admin['role']->toArray();
            if(empty($role)){
                $auth = [];
            }else{
                $roleIds = array_column($role,'id');
                if(in_array(1,$roleIds)){
                    $auth = $AdminMenu->getAllAdminMenu(['seller_id'=>1])['data']->toArray();
                }else{
                    $menuIds = array_column($role,'auth');
                    $whereIn = array_unique($menuIds);
                    $auth = $AdminMenu -> getAllAdminMenu(['id','in',$whereIn])['data']->toArray();
                }
            }
            $token = Jwt::token([
                'uid' => $admin['id'],
                'name' => $admin['name'],
                'seller_id' => $admin['seller_id']
            ]);
            $loginTime = time();
            // 登录日志
            $data = [
                'seller_id' => $admin['seller_id'],
                'admin_id' => $admin['id'],
                'admin_name' => $admin['name'],
                'title' => $admin['name'].'登录后台系统',
                'ip' => request()->ip(),
                'agent' => request()->header()['user-agent'],
                'login_time' => $loginTime
            ];
            event('AdminLoginLog',$data);
            // 更新最后登录时间
            $admin->last_login_time = $loginTime;
            $admin->save();
            return jsonReturn(0, '登录成功', ['token' => (string)$token]);
        }
    }

}
